package com.biodiv.community.service.post.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biodiv.community.converter.PostConverter;
import com.biodiv.community.entity.Post;
import com.biodiv.community.entity.User;
import com.biodiv.community.enums.PostTypeEnum;
import com.biodiv.community.mapper.PostMapper;
import com.biodiv.community.mapper.UserMapper;
import com.biodiv.community.request.post.PostDTO;
import com.biodiv.community.response.post.PostVO;
import com.biodiv.community.service.post.PostService;
import com.biodiv.community.threadLocal.UserContext;
import com.biodiv.community.base.PageResult;
import com.biodiv.community.base.PageDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author XIE
 * @description 针对表【post(帖子信息表)】的数据库操作Service实现
 * @createDate 2025-06-14 15:55:04
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PostServiceImpl implements PostService {

    private final UserMapper userMapper;
    private final PostMapper postMapper;

    /**
     * 添加帖子
     *
     * @param postDTO 帖子数据传输对象
     * @return
     */
    @Override
    public Long addPost(PostDTO postDTO) {
        Long userId = UserContext.getUserId();
        // 校验类型指定社区
        checkType(postDTO);
        if (userId == null) {
            throw new IllegalArgumentException("用户id为空");
        }
        if (postDTO == null) {
            throw new IllegalArgumentException("新增帖子参数为空");
        }
        LocalDateTime now = LocalDateTime.now();
        // 组装实体

        Post postEntity = PostConverter.INSTANCE.convert(postDTO);
        postEntity.setUserId(userId);
        postEntity.setPostTime(now);
        postEntity.setCreateTime(now);
        postEntity.setUpdateTime(now);
        try {
            //添加帖子
            postMapper.insert(postEntity);
            return postEntity.getId();
        } catch (Exception e) {
            // 记录日志并抛出异常
            log.error("添加帖子失败, 用户ID: {}, 帖子标题: {}", userId, postDTO.getTitle(), e);
            throw e;
        }
    }

    /**
     * 删除帖子
     * @param id
     */
    @Override
    public void deletePost(Integer id) {
        // 查询校验帖子
        Post post = postMapper.selectById(id);
        if (post == null) {
            throw new IllegalArgumentException("删除帖子不存在");
        }
        // 校验用户
        Long userId = post.getUserId();
        if (!userId.equals(UserContext.getUserId())) {
            throw new IllegalArgumentException("无权删除他人帖子！");
        }
        try {
            // 删除帖子
            postMapper.deleteById(id);
        } catch (Exception e) {
            // 记录日志并抛出异常
            log.error("删除失败: {}", id, e);
            throw e;
        }

    }

    /**
     * 根据帖子id查询帖
     * @param id
     * @return
     */
    @Override
    public PostVO getPostById(Integer id) {
        Post post = postMapper.selectById(id);
        if (post == null) {
            throw new IllegalArgumentException("帖子不存在");
        }
        PostVO postResponseVO = PostConverter.INSTANCE.convert(post);
        // 根据用户id查询用户，名称、头像
        User user = userMapper.selectById(post.getUserId());
        //后续解开
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        postResponseVO.setNickName(user.getNickName());
        postResponseVO.setAvatar(user.getAvatar());
        return postResponseVO;
    }




    /**
     * 修改帖子
     * @param id
     * @param postDTO
     */
    @Override
    public void updatePost(Long id, PostDTO postDTO) {
        Long userId = UserContext.getUserId();
        Post post = postMapper.selectById(id);
        checkType(postDTO);
        if (post == null) {
            throw new IllegalArgumentException("帖子不存在");
        }
        if (!post.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权修改他人帖子！");
        }
        Post bean = BeanUtil.toBean(postDTO, Post.class);
        bean.setId(id);
        postMapper.updateById(bean);
    }

    /**
     * 帖子列表
     * @param pageDTO
     * @return
     */
    @Override
    public PageResult<PostVO> postList(PageDTO pageDTO) {

        // 所有用户的id
        List<Long> userIds = new ArrayList<>();

        // 查到所有的帖子
        Page<Post> page = new Page<>();
        // 把帖子拿出来转为vo，少了头像和昵称
        List<PostVO> collect = page.getRecords().stream().map(
                        post -> {
                            PostVO postVO = BeanUtil.copyProperties(post, PostVO.class);
                            userIds.add(post.getUserId());
                            // conversion(post, postVO);
                            return postVO;
                        })
                .collect(Collectors.toList());
        //  根据用户id查询用户表，key：用户id，value：用户本身
        Map<Long, User> map = userMapper.selectBatchIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));
        // 补全VO
        collect.forEach(postVO -> {
            User user = map.get(postVO.getUserId());
            postVO.setNickName(user.getNickName());
            postVO.setAvatar(user.getAvatar());
        });
        // 返回带分页信息的 VO 列表
        return null;
    }


    /**
     * 校验帖子类型
     * @param postDTO
     */
    private void checkType(PostDTO postDTO) {
        String type = postDTO.getType();
        if (PostTypeEnum.equals(PostTypeEnum.PUBLIC_POST,type) || PostTypeEnum.equals(PostTypeEnum.SYSTEM_NOTICE,type)){
            if (!Objects.equals(postDTO.getCommunityId(), "")) {
                throw new IllegalArgumentException("非社区帖无法指定社区！");
            }
        }
        if (PostTypeEnum.equals(PostTypeEnum.COMMUNITY_PUBLIC_POST,type) ||
                PostTypeEnum.equals(PostTypeEnum.COMMUNITY_PRIVATE_POST,type)||
                PostTypeEnum.equals(PostTypeEnum.COMMUNITY_NOTICE,type)) {
            if (Objects.equals(postDTO.getCommunityId(), "")) {
                throw new IllegalArgumentException("社区帖须指定社区！");
            }
        }
    }


}



